package com.bw.controller;

import com.alibaba.fastjson.JSON;
import com.bw.domain.User;
import com.bw.service.UserService;
import com.bw.util.UserLoginValid;
import com.bw.util.UserRegValid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    UserService userService;
    // 注册2-1 跳转到注册页面
    @GetMapping("reg")
    public String reg(User user){

        return "reg";
    }

    // 注册2-2 执行注册
    @PostMapping("reg")
    public String reg(@Validated(UserRegValid.class)  User user, BindingResult result){
        if(result.hasErrors()){ //校验未通过
            return "reg";
        }

        if(userService.add(user)>0) {
            System.out.println("注册成功：" + user);
            return "redirect:login";//注册成功，重定向到登录页面
        }

        return "reg";
    }



    // 登录2-1 跳转到登录页面
    @GetMapping("login")
    public String login(User user,HttpServletRequest request,Model model) throws UnsupportedEncodingException {

        //获取cookie
        Cookie[] cookies = request.getCookies();
        if(cookies!=null &&cookies.length>0){//
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if(name.equals("GOODS_USER")){//如果名字和存储的一样，则获取cookie的value
                    System.out.println("name==================>"+name);
                     String value = cookie.getValue();
                    String decodeValue = URLDecoder.decode(value, "UTF-8");//解码
                    user = JSON.parseObject(decodeValue, User.class);//把cookie的对象解析为user
                    model.addAttribute("user",user);
                }
            }
        }


        return "login";
    }

    // 登录2-1 执行登录  , flag=1  下次自动登录
    @PostMapping("login")
    public String login(@Validated(UserLoginValid.class)  User user, BindingResult result,String flag, HttpSession session ,HttpServletResponse response, Model model) throws UnsupportedEncodingException {
        if(result.hasErrors()){ //校验未通过
         //   List<ObjectError> allErrors = result.getAllErrors();
           // System.out.println(allErrors);
            return "login";
        }
        User u = userService.login(user);//
        if(null!=u){//如果返回值不为null .则表示登录成功
            System.out.println("登录成功："+u);
            if(flag!=null&&flag.equals("1")) {//如果用户选中记录十天免登录
                String userstr = JSON.toJSONString(u);//把登录 对象转为json
                String encodeUserstr = URLEncoder.encode(userstr, "UTF-8");//编码
                Cookie cookie = new Cookie("GOODS_USER", encodeUserstr);
                cookie.setMaxAge(60 * 60 * 24 * 10);//10天的有效期 默认单位是秒
                response.addCookie(cookie);//把goods_user 放入cookie 并传递给浏览器
            }
            //存入session
            session.setAttribute("user",u);
           //跳转的list
            return "redirect:list";
        }
        model.addAttribute("message","登录失败，检查用户名或密码");
       return "login";
    }


    //用户注销
    @GetMapping("logout")
    public String logout(HttpSession session,HttpServletRequest request,HttpServletResponse response){

        session.invalidate();//清楚当前用户所有的session 信息
        Cookie[] cookies = request.getCookies();
        if(cookies!=null &&cookies.length>0){//
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if(name.equals("GOODS_USER")){//如果名字和存储的一样，则获取cookie的value
                    cookie.setMaxAge(0);//销毁cookie
                    response.addCookie(cookie);
                }
            }
        }
        return "redirect:login";//重定向到登录页面
    }

    @GetMapping("hello")
    public void hello(){
        System.out.println("目标方法的调用。。。。。。");
    }
}
